package com.zbkj.crmeb.task.plat.tiktok;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.crmeb.core.common.CommonResult;
import com.crmeb.core.config.RestTemplateConfig;
import com.crmeb.core.exception.ExceptionCodeEnum;
import com.doudian.open.api.sku_editPrice.SkuEditPriceRequest;
import com.doudian.open.api.sku_editPrice.SkuEditPriceResponse;
import com.doudian.open.api.sku_editPrice.param.SkuEditPriceParam;
import com.doudian.open.api.sku_syncStock.SkuSyncStockRequest;
import com.doudian.open.api.sku_syncStock.SkuSyncStockResponse;
import com.doudian.open.api.sku_syncStock.param.SkuSyncStockParam;
import com.doudian.open.core.AccessToken;
import com.doudian.open.core.AccessTokenBuilder;
import com.factory.TaskParamsDto;
import com.factory.TaskProcessEngineFactory;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.taobao.pac.sdk.cp.dataobject.response.SCF_ABC_QUERY_BALANCE.Acc;
import com.utils.PriceUtil;
import com.utils.monitor.DingMsgEnum;
import com.utils.monitor.DingTalkMsgUtil;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.service.ICategoryMatchService;
import com.zbkj.crmeb.enums.AreaTypeEnum;
import com.zbkj.crmeb.enums.BusinessTypeEnums;
import com.zbkj.crmeb.enums.plat.PlatPushStatusEnums;
import com.zbkj.crmeb.handler.orderproduct.OrderProductInterface;
import com.zbkj.crmeb.plat.by.dto.ByCommonConstant;
import com.zbkj.crmeb.plat.by.dto.Result;
import com.zbkj.crmeb.plat.by.service.PlatProductService;
import com.zbkj.crmeb.plat.enums.MerPlatEnums;
import com.zbkj.crmeb.store.dao.StoreOrderDao;
import com.zbkj.crmeb.store.model.Relation;
import com.zbkj.crmeb.store.model.StoreProduct;
import com.zbkj.crmeb.store.model.StoreProductAttrValue;
import com.zbkj.crmeb.store.response.StoreProductResponse;
import com.zbkj.crmeb.store.service.*;
import com.zbkj.crmeb.task.plat.AbstractPlatOperate;
import com.zbkj.crmeb.tools.model.MoneyExchange;
import com.zbkj.crmeb.tools.service.MoneyExchangeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 抖店捞取
 *
 * @author: wsl
 * @date: 2024/1/29 0029 22:08
 * @ClassName: BieYangOrderTask
 */
@Component("tikTokProductTask")
@Configuration
@Slf4j
public class TikTokProductTask extends AbstractPlatOperate<TaskParamsDto> implements ApplicationRunner {
    private static final Logger logger = LoggerFactory.getLogger(TikTokProductTask.class);

    @Resource
    private PlatProductService platProductService;

    @Autowired
    RestTemplateConfig restTemplateConfig;
    @Autowired
    private StoreOrderService storeOrderService;
    @Autowired
    private StoreOrderInfoService storeOrderInfoService;
    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    private RelationService relationService;
    @Autowired
    private StoreProductAttrService storeProductAttrService;
    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;
    @Resource
    private StoreOrderDao storeOrderDao;
    @Resource
    private StoreBrandService storeBrandService;
    @Resource
    private ICategoryMatchService categoryMatchService;
    @Resource
    private PriceUtil priceUtil;
    @Resource
    private MoneyExchangeService moneyExchangeService;
    @Qualifier("tikTokOrderProductHandler")
    private OrderProductInterface orderProductInterface;

    @Autowired
    private Redisson redisson;

    private static String envValue;
    @Value("${spring.profiles.active}")
    public void setEnv(String env) {
        envValue = env;
    }

    private static final String LOCK_KEY = "tikTokProductTask";

    @Override
    public void run(ApplicationArguments args) throws Exception {
//        if (Objects.equals(envValue,"test")||Objects.equals(envValue,"dev")){
//            log.info("当前环境暂不推送商品, env:{}",envValue);
//            return;
//        }
//        new Thread(()->{
//            RLock rLock = redisson.getLock(LOCK_KEY);
//            while (true){
//                try {
//                    if (!rLock.tryLock(3, TimeUnit.SECONDS)) {
//                        log.warn("未获取到锁，稍后尝试");
//                        continue;
//                    }
//                    TaskProcessEngineFactory.executeTask();
////                    checkByProductStockV2();
////                    checkByProductPriceV2();
//                    Thread.sleep(RandomUtils.nextInt(1000, 3000));
//                } catch (Exception e) {
//                    log.error("商品轮询任务执行失败");
//                } finally {
//                    rLock.unlock();
//                }
//            }
//        }).start();
    }

    @Override
    public Result execute(TaskParamsDto taskParamsDto) {
        MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
        mockHttpServletRequest.addHeader("mer_id", String.valueOf(taskParamsDto.getMerId()));
        ServletRequestAttributes servletRequestAttributes = new ServletRequestAttributes(mockHttpServletRequest);
        RequestContextHolder.setRequestAttributes(servletRequestAttributes);
        taskParamsDto.getPlatProductRequest().setSyncTask(false);
        CommonResult<List<String>> commonResult = null;
        try {
            taskParamsDto.getPlatProductRequest().setSyncTask(false);
            commonResult = platProductService.pushProduct(taskParamsDto.getPlatProductRequest(), Integer.valueOf(StringUtils.isNotBlank(taskParamsDto.getMerId()) ? taskParamsDto.getMerId() : MerPlatEnums.BY_126.getMerId().toString()));
            if (commonResult.getCode() == ExceptionCodeEnum.SUCCESS.getCode()) {
                return Result.getSuccessResult();
            }
            if (commonResult.getCode() != ExceptionCodeEnum.SUCCESS.getCode()) {
//            DingTalkMsgUtil.sendMsg(DingMsgEnum.PLAT,"推送商品失败,productId:+"+taskParamsDto.getPlatProductRequest().getProductId()+",:"+commonResult.getMessage());
                log.error("推送商品失败,productId:{},:{}", taskParamsDto.getPlatProductRequest().getProductId(), commonResult.getMessage());
            }
        } catch (Exception e) {
            logger.error("推送商品失败,查询商品异常:", e);
        } finally {
            RequestContextHolder.resetRequestAttributes();
        }
        return Result.getFailureResult("execute error", commonResult.getMessage());
    }

    @XxlJob("checkTikTokProductPrice")
    public void checkTikTokProductPriceV2() {
        String logID = UUID.randomUUID().toString();
        logger.info("logID:[{}]", logID);
        logger.info("[{}] checkTikTokProductPrice入口", logID);
        List<Integer> merIds = new ArrayList<>();
        merIds.add(TikTokApi.getMerId_150());
        BusinessTypeEnums productRelationsType = null;
        BusinessTypeEnums skuRelationsType = null;
        for (Integer merId : merIds) {
            if (merId == TikTokApi.getMerId_150().intValue()) {
                productRelationsType = BusinessTypeEnums.PUSH_PRODUCT_PLAT_OF_DY;
                skuRelationsType = BusinessTypeEnums.PUSH_SKU_PLAT_OF_DY;
                checkTikTokProductPrice(logID, merId, productRelationsType, skuRelationsType);
            }
        }
    }


    public void checkTikTokProductPrice(String logID, Integer merId, BusinessTypeEnums productRelationsType, BusinessTypeEnums skuRelationsType) {
        logger.info("[{}] checkTikTokProductPrice 方法入口：{},{},{}", logID, merId, productRelationsType.getDesc(), skuRelationsType.getDesc());
        try {
            // mock个请求
            MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
            mockHttpServletRequest.addHeader("mer_id", String.valueOf(merId));
            ServletRequestAttributes servletRequestAttributes = new ServletRequestAttributes(mockHttpServletRequest);
            RequestContextHolder.setRequestAttributes(servletRequestAttributes);
            // 捞上架数据
            int count = relationService.count(Wrappers.<Relation>lambdaQuery().eq(Relation::getSubCode, ByCommonConstant.TIKTOK_UP)
                    .eq(Relation::getBusinessType, productRelationsType.getCode()));
            if (count == 0) {
                logger.error("[{}] 抖店商家商品检查任务,未扫描到已上架商品", logID);
                return;
            }
            // 需要更新价格sku
            List<StoreProductAttrValue> needUpdateSkus = new ArrayList<>();
            int maxPage = (count + 499) / 500;
            int pageNo = 1;
            while (pageNo <= maxPage) {
                Page<Relation> page = PageHelper.startPage(pageNo, 500);
                try {
                    relationService.list(Wrappers.<Relation>lambdaQuery().eq(Relation::getSubCode, ByCommonConstant.TIKTOK_UP)
                            .eq(Relation::getBusinessType, productRelationsType.getCode()).orderByDesc(Relation::getId));
                    List<Relation> productRelations = page.getResult();
                    logger.info("[{}] productRelations：{}", logID, JSON.toJSONString(productRelations));
                    if (CollectionUtils.isEmpty(productRelations)) {
                        throw new RuntimeException("数据查询异常");
                    }
                    // 检查sku信息
                    List<Integer> productIds = productRelations.stream().map(k -> Integer.valueOf(k.getBusinessCode())).collect(Collectors.toList());
                    List<StoreProductAttrValue> attrValues = storeProductAttrValueService.listRelationInfoByProductId(productIds, skuRelationsType);
                    logger.info("[{}] attrValues：{}", logID, JSON.toJSONString(attrValues));

                    if (CollectionUtils.isEmpty(attrValues)) {
                        continue;
                    }
                    Map<Integer, List<StoreProductAttrValue>> skuMap = attrValues.stream().collect(Collectors.groupingBy(StoreProductAttrValue::getProductId));
                    logger.info("[{}] skuMap：{}", logID, JSON.toJSONString(skuMap));

                    List<StoreProduct> storeProducts = storeProductService.listByIds(productIds);
                    logger.info("[{}] storeProducts：{}", logID, JSON.toJSONString(storeProducts));

                    Map<Integer, StoreProduct> productMap = storeProducts.stream().collect(Collectors.toMap(StoreProduct::getId, v -> v));
                    Map<Integer, Relation> productRelationMap = productRelations.stream().collect(Collectors.toMap(k -> Integer.valueOf(k.getBusinessCode()), v -> v));

                    for (Map.Entry<Integer, List<StoreProductAttrValue>> entry : skuMap.entrySet()) {
                        Integer productId = entry.getKey();
                        List<StoreProductAttrValue> skus = entry.getValue();
                        StoreProduct storeProduct = productMap.get(productId);
                        Relation relation = productRelationMap.get(productId);
                        if (CollectionUtils.isEmpty(skus) || null == storeProduct) {
                            logger.error("[{}] continue了吧：{} ,{}", logID, JSON.toJSONString(skus), JSON.toJSONString(storeProduct));

                            continue;
                        }
                        priceUtil.calcProductValuePrice(skus, merId, storeProduct, AreaTypeEnum.CN.getType(), null, false, null, true, null);
                        // 过滤需要更新价格的sku
                        List<StoreProductAttrValue> needUpdatePriceList = needUpdatePriceProducts(logID, skus, relation, productRelationsType, skuRelationsType);
                        log.info("[{}] needUpdatePriceList:{}", logID,  JSON.toJSONString(needUpdatePriceList));
                        log.info("[{}] needUpdateSkus:{}", logID,  JSON.toJSONString(needUpdateSkus));
                        if (CollectionUtils.isNotEmpty(needUpdatePriceList)) {
                            needUpdateSkus.addAll(needUpdatePriceList);
                        }

                    }
                } catch (Exception e) {
                    logger.error("[{}] 抖店商家商品价格检查任务,查询商品异常", logID, e);
                } finally {
                    pageNo++;
                }
            }
            if (CollectionUtils.isNotEmpty(needUpdateSkus)) {
                AccessToken accessToken = AccessTokenBuilder.build(TikTokApi.getShopId(merId));
                doUpdateSkusPrice(logID,needUpdateSkus, accessToken);
            }
        } catch (Exception e) {
            logger.error("[{}] 抖店商家商品价格检查任务,查询商品异常:", logID, e);
        } finally {
            RequestContextHolder.resetRequestAttributes();
        }


    }

    private void doUpdateSkusPrice(String logID,List<StoreProductAttrValue> updateSkus,AccessToken accessToken) {
        logger.info("[{}] doUpdateSkusPrice 方法入口：{}，{}，{}", logID, JSON.toJSONString(accessToken),JSON.toJSONString(updateSkus));

        try {
            for (StoreProductAttrValue skus : updateSkus) {
                String srcPrice = skus.getPushRelation().getFeature(ByCommonConstant.PLAT_ORIGINAL_PRICE);

                String dyProductId = skus.getPushRelation().getFeature(ByCommonConstant.DY_PRODUCT_ID);
                String dyOutProductId = skus.getPushRelation().getFeature(ByCommonConstant.DY_OUT_PRODUCT_ID);
                String dySKuId = skus.getPushRelation().getFeature(ByCommonConstant.DY_SKU_ID);
                String dyOutSKuId = skus.getPushRelation().getFeature(ByCommonConstant.DY_OUT_SKU_ID);
                Thread.sleep(RandomUtils.nextInt(10, 100));

                // 组装参数
                // 更新价格
                String salePrice = skus.getPushRelation().getFeature(ByCommonConstant.PLAT_SALE_PRICE);
                String originPrice = skus.getPushRelation().getFeature(ByCommonConstant.PLAT_ORIGINAL_PRICE);
                SkuEditPriceRequest request = new SkuEditPriceRequest();
                SkuEditPriceParam param = request.getParam();
                param.setPrice(new BigDecimal(salePrice).longValue());
                param.setSkuId(Long.parseLong(dySKuId));
                param.setOutSkuId(Long.parseLong(dyOutSKuId));
                param.setProductId(Long.parseLong(dyProductId));
                param.setOutProductId(Long.parseLong(dyOutProductId));
                logger.info("[{}] 抖店同步价格请求:{}", logID, JSON.toJSONString(request));
                SkuEditPriceResponse response = request.execute(accessToken);
                logger.error("[{}] 抖店同步价格响应:{}", logID, JSON.toJSONString(response));

                // 随机休眠一下，下次做下限流
                if (response.isSuccess()) {
                    skus.getPushRelation().addFeature(ByCommonConstant.PLAT_ORIGINAL_PRICE, salePrice);
                    skus.getPushRelation().addFeature(ByCommonConstant.PLAT_SALE_PRICE, originPrice);
                    relationService.updateById(skus.getPushRelation());
                }
                String res = JSON.toJSONString(param);
                DingTalkMsgUtil.sendMsg(DingMsgEnum.PLAT,String.format("抖店更新价格，原价:%s ,更新价格:%s ,接口返回:%s",srcPrice,salePrice, res));
                logger.error("[{}] 抖店更新价格，原价:{} ,更新价格:{} ,接口返回:{}", logID, srcPrice, salePrice, res);
            }
        } catch (Exception e) {
            log.error("[{}] 更新sku价格异常:", logID, e);
        }
    }

    private Object assembledPriceRequest(StoreProductAttrValue skus) {
        return null;
    }

    private List<StoreProductAttrValue> needUpdatePriceProducts(String logID,List<StoreProductAttrValue> attrValues, Relation relation, BusinessTypeEnums productRelationsType, BusinessTypeEnums skuRelationsType) {
        logger.info("[{}] needUpdatePriceProducts：{}, {}, {}, {}", logID, JSON.toJSONString(attrValues), JSON.toJSONString(relation), productRelationsType.getDesc(), skuRelationsType.getDesc());

        // 移除掉库存为0
        attrValues.removeIf(k -> k.getStock() <= 0);
        if (CollectionUtils.isEmpty(attrValues)) {
            return null;
        }
        // 金额加上一二段费用
        attrValues.forEach(v -> v.setPrice(getValidPrice(v.getPrice()).add(getValidPrice(v.getFirstPrice())).add(getValidPrice(v.getSecondPrice()))));
        // 库存>0且价格最低的sku
        Map<String, StoreProductAttrValue> sortMap = attrValues.stream().filter(k -> k.getStock() > 0).collect(Collectors.toMap(StoreProductAttrValue::getSuk, v -> v, (v1, v2) -> {
            if (v1.getPrice().compareTo(v2.getPrice()) <= 0) {
                return v1;
            }
            return v2;
        }));
        // 获取上架的sku
        List<StoreProductAttrValue> srcSkus = storeProductAttrValueService.
                listRelationInfoByProductId(Collections.singletonList(Integer.valueOf(relation.getBusinessCode())), skuRelationsType);
        // 移除掉没有推送关联或者未上架的sku
        srcSkus.removeIf(k -> null == k.getPushRelation() || !Objects.equals(k.getPushRelation().getSubCode(), ByCommonConstant.TIKTOK_UP));
        logger.info("[{}] srcSkus：{}", logID, JSON.toJSONString(srcSkus));

        if (CollectionUtils.isEmpty(srcSkus)) {
            return null;
        }
        List<StoreProductAttrValue> needUpdateList = new ArrayList<>();
        // 获取最终需要更新的数据
        for (StoreProductAttrValue srcSku : srcSkus) {
            String suk = srcSku.getSuk();
            // 用规格来匹配
            if (!sortMap.containsKey(suk)) {
                logger.info("[{}] continue了哦：{},{}", logID, JSON.toJSONString(sortMap), suk);

                continue;
            }
            StoreProductAttrValue sku = sortMap.get(suk);
            BigDecimal baseExchange = new BigDecimal("1");
            MoneyExchange moneyExchange = moneyExchangeService.getById(23);
            if (null != moneyExchange && StringUtils.isNotBlank(moneyExchange.getBankConversionPri())) {
                baseExchange = new BigDecimal(moneyExchange.getBankConversionPri());
            }
            String originPrice = srcSku.getPushRelation().getFeature(ByCommonConstant.PLAT_ORIGINAL_PRICE);
            BigDecimal purchasePrice = srcSku.getPrice()
                    .divide(baseExchange, 2, RoundingMode.DOWN).multiply(BigDecimal.valueOf(100L)).setScale(2, RoundingMode.DOWN);
            ChannelMerchant mockChannelMerchant = new ChannelMerchant();
            StoreProduct storeProduct = storeProductService.getById(sku.getProductId());

            BigDecimal taxPriceNew = priceUtil.getTaxPriceNew(storeProduct, AreaTypeEnum.CN.getType(),
                    purchasePrice, mockChannelMerchant, purchasePrice, false, false, false);
            BigDecimal taxPrice = srcSku.getTaxPrice().compareTo(taxPriceNew) >= 0 ? sku.getTaxPrice() : taxPriceNew;


            BigDecimal newOriginPrice = purchasePrice.multiply(new BigDecimal("100"));

            BigDecimal newSalePrice = purchasePrice.add(taxPrice).setScale(2, RoundingMode.DOWN).multiply(new BigDecimal("100"));

            // 平台原价为空或者差价绝对值超过了固定点
            boolean flag = StringUtils.isBlank(srcSku.getPushRelation().getFeature(ByCommonConstant.PLAT_ORIGINAL_PRICE))
                    || outPriceThreshold(srcSku.getPushRelation().getFeature(ByCommonConstant.PLAT_ORIGINAL_PRICE), newOriginPrice, baseExchange);
            logger.info("[{}] 平台原价为空或者差价绝对值超过了固定点flag：{}", logID, flag);

            if (flag) {
                srcSku.getPushRelation().addFeature(ByCommonConstant.NEW_PLAT_ORIGINAL_PRICE, newOriginPrice.toString());
                srcSku.getPushRelation().addFeature(ByCommonConstant.NEW_PLAT_SALE_PRICE, newSalePrice.toString());
                srcSku.getPushRelation().addFeature(ByCommonConstant.PUSH_PRICE, newSalePrice.toString());
                needUpdateList.add(srcSku);
            }
        }
        return needUpdateList;
    }

    private boolean outPriceThreshold(String platPrice, BigDecimal price, BigDecimal baseExchange) {
        String newPrice = String.valueOf(price.divide(baseExchange, 2, RoundingMode.DOWN).multiply(BigDecimal.valueOf(100L)).setScale(2, RoundingMode.DOWN).intValue());
        // 最大差值
        double maxDiff = Integer.parseInt(platPrice) * 0.02;
        return Math.abs(Integer.parseInt(newPrice) - Integer.parseInt(platPrice)) > maxDiff;
    }

    private BigDecimal getValidPrice(BigDecimal value) {
        return null == value || value.compareTo(BigDecimal.ZERO) <= 0 ? BigDecimal.ZERO : value;
    }

    @XxlJob("checkTikTokProductStock")
    public void checkTikTokProductStock() {
        String logID = UUID.randomUUID().toString();
        logger.info("logID:[{}]", logID);
        logger.info("[{}] checkTikTokProductStock入口", logID);
        List<Integer> merIds = new ArrayList<>();
        merIds.add(TikTokApi.getMerId_150());
        BusinessTypeEnums productRelationsType = null;
        BusinessTypeEnums skuRelationsType = null;
        for (Integer merId : merIds) {
            if (merId == TikTokApi.getMerId_150().intValue()) {
                productRelationsType = BusinessTypeEnums.PUSH_PRODUCT_PLAT_OF_DY;
                skuRelationsType = BusinessTypeEnums.PUSH_SKU_PLAT_OF_DY;
                checkTikTokProductStock(logID,merId, productRelationsType, skuRelationsType);
            }
        }
    }

    public void checkTikTokProductStock(String logID,Integer merId, BusinessTypeEnums productRelationsType, BusinessTypeEnums skuRelationsType) {
        logger.info("[{}] checkTikTokProductStock方法入口：{},{},{}", logID, merId, productRelationsType.getDesc(), skuRelationsType.getDesc());
        // 捞上架数据
        int count = relationService.count(Wrappers.<Relation>lambdaQuery().eq(Relation::getSubCode, ByCommonConstant.TIKTOK_UP)
                .eq(Relation::getBusinessType, productRelationsType.getCode()));
        if (count == 0) {
            logger.error("[{}] 抖店商家商品检查任务,未扫描到已上架商品", logID);
            return;
        }
        int maxPage = (count + 499) / 500;
        int pageNo = 1;
        while (pageNo <= maxPage) {
            Page<Relation> page = PageHelper.startPage(pageNo, 500);
            try {
                relationService.list(Wrappers.<Relation>lambdaQuery().eq(Relation::getSubCode, ByCommonConstant.TIKTOK_UP)
                        .eq(Relation::getBusinessType, productRelationsType.getCode()).orderByDesc(Relation::getId));
                List<Relation> productRelations = page.getResult();
                logger.info("[{}] productRelations：{}", logID, JSON.toJSONString(productRelations));
                if (CollectionUtils.isEmpty(productRelations)) {
                    throw new RuntimeException("数据查询异常");
                }
                // 检查sku信息
                List<Integer> productIds = productRelations.stream().map(k -> Integer.valueOf(k.getBusinessCode())).collect(Collectors.toList());

                List<StoreProductAttrValue> attrValues = storeProductAttrValueService.listRelationInfoByProductId(productIds, skuRelationsType);
                logger.info("[{}] attrValues：{}", logID, JSON.toJSONString(attrValues));

                if (CollectionUtils.isEmpty(attrValues)) {
                    throw new RuntimeException("SKU数据为空");
                }
                Map<Integer, List<StoreProductAttrValue>> map = filterSkuInfos(attrValues);
                logger.info("[{}] map：{}", logID, JSON.toJSONString(map));

                if (MapUtils.isEmpty(map)) {
                    continue;
                }
                for (Relation relation : productRelations) {
                    Integer productId = Integer.valueOf(relation.getBusinessCode());
                    if (!map.containsKey(productId)) {
                        logger.error("[{}] continue了呀：{},{}", logID, JSON.toJSONString(map), productId);
                        continue;
                    }
                    List<StoreProductAttrValue> storeProductAttrValues = map.get(productId);
                    AccessToken accessToken = AccessTokenBuilder.build(TikTokApi.getShopId(merId));
                    logger.info("[{}] accessToken：{}", logID, JSON.toJSONString(accessToken));
                    updateProduct(logID, accessToken ,relation, storeProductAttrValues);
                }
            } catch (Exception e) {
                logger.error("[{}] 抖店商家商品检查任务,查询商品异常", logID, e);
            } finally {
                pageNo++;
            }
        }
    }

    private void updateProduct(String logID,AccessToken accessToken, Relation relation, List<StoreProductAttrValue> storeProductAttrValues) {
        logger.info("[{}] updateProduct方法入口：{}，{}，{}", logID, JSON.toJSONString(accessToken),JSON.toJSONString(relation),JSON.toJSONString(storeProductAttrValues));
        if (CollectionUtils.isEmpty(storeProductAttrValues)) {
            return;
        }
        List<StoreProductAttrValue> downSkus = new ArrayList<>();
        List<StoreProductAttrValue> updateSkus = new ArrayList<>();
        for (StoreProductAttrValue storeProductAttrValue : storeProductAttrValues) {
            if (storeProductAttrValue.getStock() <= 0) {
                downSkus.add(storeProductAttrValue);
                continue;
            }
            updateSkus.add(storeProductAttrValue);
        }
        try {
            if (CollectionUtils.isNotEmpty(downSkus)) {
                doDownSkus(logID,accessToken,relation, downSkus);
            }
        } catch (Exception e) {
            logger.error("[{}] 商品下架异常:", logID, e);
        }
        try {
            if (CollectionUtils.isNotEmpty(updateSkus)) {
                doUpdateSkus(logID,accessToken,relation, updateSkus);
            }
        } catch (Exception e) {
            logger.error("[{}] 更新商品库存异常:", logID, e);
        }

    }

    private void doUpdateSkus(String logID,AccessToken accessToken,Relation relation, List<StoreProductAttrValue> updateSkus) {
        logger.info("[{}] doUpdateSkus 方法入口：{}，{}，{}", logID, JSON.toJSONString(accessToken),JSON.toJSONString(relation),JSON.toJSONString(updateSkus));

        for (StoreProductAttrValue skus : updateSkus) {
            try {
                Thread.sleep(RandomUtils.nextInt(10, 100));
            } catch (InterruptedException e) {
                logger.error("[{}] InterruptedException：{}", logID, e);
                throw new RuntimeException(e);
            }

            String dyProductId = skus.getPushRelation().getFeature(ByCommonConstant.DY_PRODUCT_ID);
            String dyOutProductId = skus.getPushRelation().getFeature(ByCommonConstant.DY_OUT_PRODUCT_ID);
            String dySKuId = skus.getPushRelation().getFeature(ByCommonConstant.DY_SKU_ID);
            String dyOutSKuId = skus.getPushRelation().getFeature(ByCommonConstant.DY_OUT_SKU_ID);
            SkuSyncStockRequest request = new SkuSyncStockRequest();
            SkuSyncStockParam param = request.getParam();
            param.setSkuId(StringUtils.isEmpty(dySKuId) ? 0L : Long.parseLong(dySKuId));
            param.setOutSkuId(StringUtils.isEmpty(dyOutSKuId) ? 0L : Long.parseLong(dyOutSKuId));
            param.setProductId(StringUtils.isEmpty(dyProductId) ? 0L : Long.parseLong(dyProductId));
            param.setOutProductId(StringUtils.isEmpty(dyOutProductId) ? 0L : Long.parseLong(dyOutProductId));
            param.setOutWarehouseId("dy123");
            param.setIncremental(false);
            param.setStockNum(skus.getStock().longValue());
            logger.error("[{}] 抖店同步库存请求:{}", logID, JSON.toJSONString(request));
            SkuSyncStockResponse response = request.execute(accessToken);
            logger.error("[{}] 抖店同步库存响应:{}", logID, JSON.toJSONString(response));
            if (response.isSuccess()) {
                skus.getPushRelation().addFeature(ByCommonConstant.ORIGIN_STOCK, String.valueOf(skus.getStock()));
                skus.getPushRelation().setSubCode(PlatPushStatusEnums.DY_UP.getCode());
                relationService.updateById(skus.getPushRelation());
            }
            DingTalkMsgUtil.sendMsg(DingMsgEnum.PLAT, "抖店更新库存返回:" + JSON.toJSONString(param));
            logger.error("[{}] 抖店更新库存返回:{}", logID, JSON.toJSONString(param));
        }

    }

    private void doDownSkus(String logID,AccessToken accessToken,Relation relation, List<StoreProductAttrValue> downSkus) {
        logger.info("[{}] doDownSkus 方法入口：{}，{}，{}", logID, JSON.toJSONString(accessToken),JSON.toJSONString(relation),JSON.toJSONString(downSkus));
        for (StoreProductAttrValue skus : downSkus) {
            try {
                Thread.sleep(RandomUtils.nextInt(10, 100));
            } catch (InterruptedException e) {
                logger.error("[{}] InterruptedException：{}", logID, e);
                throw new RuntimeException(e);
            }

            String dyProductId = skus.getPushRelation().getFeature(ByCommonConstant.DY_PRODUCT_ID);
            String dyOutProductId = skus.getPushRelation().getFeature(ByCommonConstant.DY_OUT_PRODUCT_ID);
            String dySKuId = skus.getPushRelation().getFeature(ByCommonConstant.DY_SKU_ID);
            String dyOutSKuId = skus.getPushRelation().getFeature(ByCommonConstant.DY_OUT_SKU_ID);
            SkuSyncStockRequest request = new SkuSyncStockRequest();
            SkuSyncStockParam param = request.getParam();
            param.setSkuId(Long.parseLong(dySKuId));
            param.setOutSkuId(Long.parseLong(dyOutSKuId));
            param.setProductId(Long.parseLong(dyProductId));
            param.setOutProductId(Long.parseLong(dyOutProductId));
            param.setOutWarehouseId("dy123");
            param.setIncremental(false);
            param.setStockNum(skus.getStock().longValue());
            logger.error("[{}] 抖店下架商品请求:{}", logID, JSON.toJSONString(request));
            SkuSyncStockResponse response = request.execute(accessToken);
            logger.error("[{}] 抖店下架商品响应:{}", logID, JSON.toJSONString(response));
            if (response.isSuccess()) {
                skus.getPushRelation().addFeature(ByCommonConstant.ORIGIN_STOCK, "0");
                skus.getPushRelation().addFeature(ByCommonConstant.PUSH_PLAT, "N");
                skus.getPushRelation().setSubCode(PlatPushStatusEnums.DY_DOWN.getCode());
                relationService.updateById(skus.getPushRelation());
            }
            DingTalkMsgUtil.sendMsg(DingMsgEnum.PLAT, "抖店sku下架返回:" + JSON.toJSONString(response));
            logger.error("[{}] 抖店sku下架返回:{}", logID, JSON.toJSONString(param));
        }

    }


    private Map<Integer, List<StoreProductAttrValue>> filterSkuInfos(List<StoreProductAttrValue> attrValues) {
        Iterator<StoreProductAttrValue> iterator = attrValues.iterator();
        Map<Integer, List<StoreProductAttrValue>> map = new HashMap<>();
        while (iterator.hasNext()) {
            StoreProductAttrValue attrValue = iterator.next();
            // 没有推送关系，没有上架标记，库存大于0并且上架库存和当前库存相等
            boolean flag = attrValue.getPushRelation() == null
                    || !Objects.equals(attrValue.getPushRelation().getSubCode(), ByCommonConstant.TIKTOK_UP)
                    || (Objects.equals(attrValue.getStock(), Integer.valueOf(attrValue.getPushRelation().getFeature(ByCommonConstant.ORIGIN_STOCK))));
            if (flag) {
                iterator.remove();
                continue;
            }
            map.computeIfAbsent(attrValue.getProductId(), v -> new ArrayList<>()).add(attrValue);
        }
        return map;
    }
}
